﻿
using System.Xml;
using System.Xml.XPath;
namespace InfoPathHelpers.TemplateExplorer
{
    public static class NamespaceResolution
    {
        public static XmlNamespaceManager GetNamespaceManager(XmlDocument document)
        {
            return CreateNamespaceManager(document.CreateNavigator());
        }

        public static XmlNamespaceManager GetNamespaceManager(XPathDocument document)
        {
            return CreateNamespaceManager(document.CreateNavigator());
        }

        public static XmlNamespaceManager GetNamespaceManager(XPathNavigator node)
        {
            // Clone the navigator so we don't change the position.
            var Navigator = node.Clone();
            // The node could be positioned anywhere so first move to root.
            Navigator.MoveToRoot();

            return CreateNamespaceManager(Navigator);
        }

        private static XmlNamespaceManager CreateNamespaceManager(XPathNavigator node)
        {
            var NamespaceManager = new XmlNamespaceManager(node.NameTable);
            // Move to the root element which declares the namespaces.
            node.MoveToFollowing(XPathNodeType.Element);
            // Get all namespaces.
            var Namespaces = node.GetNamespacesInScope(XmlNamespaceScope.All);
            // Add all namespaces to the NamespaceManager.
            foreach (var KeyValuePair in Namespaces)
            {
                NamespaceManager.AddNamespace(KeyValuePair.Key, KeyValuePair.Value);
            }

            return NamespaceManager;
        }
    }
}
